package com.scientific.research.gobang.utils;

import com.scientific.research.gobang.pojo.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * jwt工具类
 */
public class JwtUtils {

    public static final long USER_EXPIRE = 1000 * 60 * 60 * 24;  //用户信息一天过期
    public static final String SECRET = "WgtqaT1HNTZPZNMERGRGDJuFG86EJFOIEFJMWf"; //密钥，加盐

    /**
     * 生成jwt
     *
     * @param user
     * @return
     */
    public static String getUserToken(User user) {
        String token = Jwts.builder()
                .claim("user", user)
                .setExpiration(new Date(System.currentTimeMillis() + USER_EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
        return token;
    }

    /**
     * 校验token
     *
     * @param token
     * @return
     */
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    public static Claims checkJWT(String token) {
        try {
            final Claims claims = Jwts.parser().setSigningKey(SECRET).
                    parseClaimsJws(token).getBody();
            return claims;
        } catch (Exception e) {
        }
        return null;
    }
}
